import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../models/event_model.dart';

class WebSocketService extends GetxService {
  WebSocketChannel? _channel;
  final _eventController = StreamController<Event>.broadcast();
  final _currentApp = Rx<AppSwitchEvent?>(null);
  final _recentSwitches = RxList<AppSwitchEvent>([]);
  final _appSwitchStats = RxMap<String, int>({});
  final _appUsageDuration = RxMap<String, int>({});
  final _lastKeyPress = RxMap<String, bool>({});
  DateTime? _lastSwitchTime;

  // 获取事件流
  Stream<Event> get eventStream => _eventController.stream;
  
  // 获取当前应用信息
  Rx<AppSwitchEvent?> get currentApp => _currentApp;
  
  // 获取最近切换记录
  RxList<AppSwitchEvent> get recentSwitches => _recentSwitches;
  
  // 获取应用切换统计
  RxMap<String, int> get appSwitchStats => _appSwitchStats;
  
  // 获取应用使用时长
  RxMap<String, int> get appUsageDuration => _appUsageDuration;

  // 获取按键状态映射
  RxMap<String, bool> get lastKeyPress => _lastKeyPress;

  @override
  void onInit() {
    super.onInit();
    _connectWebSocket();
  }

  @override
  void onClose() {
    _channel?.sink.close();
    _eventController.close();
    super.onClose();
  }

  Future<WebSocketService> init() async {
    return this;
  }

  void _connectWebSocket() {
    try {
      _channel = WebSocketChannel.connect(
        Uri.parse('ws://localhost:8080/ws'),
      );

      _channel!.stream.listen(
        (message) {
          try {
            final jsonData = json.decode(message as String);
            final event = Event.fromJson(jsonData);
            _eventController.add(event);
            _handleEvent(event);
          } catch (e) {
            print('Error processing message: $e');
          }
        },
        onError: (error) {
          print('WebSocket error: $error');
          _reconnect();
        },
        onDone: () {
          print('WebSocket connection closed');
          _reconnect();
        },
      );
    } catch (e) {
      print('Error connecting to WebSocket: $e');
      _reconnect();
    }
  }

  void _reconnect() {
    Future.delayed(const Duration(seconds: 5), () {
      print('Attempting to reconnect...');
      _connectWebSocket();
    });
  }

  void _handleEvent(Event event) {
    switch (event.type) {
      case EventTypes.appSwitch:
        _handleAppSwitchEvent(AppSwitchEvent.fromJson(event.data));
        break;
      case EventTypes.keyPress:
        _handleKeyPressEvent(KeyPressEvent.fromJson(event.data));
        break;
      case EventTypes.networkTraffic:
        _handleNetworkTrafficEvent(NetworkTrafficEvent.fromJson(event.data));
        break;
    }
  }

  void _handleAppSwitchEvent(AppSwitchEvent switchEvent) {
    // 更新当前应用
    _currentApp.value = switchEvent;

    // 更新最近切换记录（保持最近20条）
    _recentSwitches.insert(0, switchEvent);
    if (_recentSwitches.length > 20) {
      _recentSwitches.removeLast();
    }

    // 更新应用切换统计
    final appName = switchEvent.targetAppName;
    _appSwitchStats[appName] = (_appSwitchStats[appName] ?? 0) + 1;

    // 更新应用使用时长
    if (_lastSwitchTime != null && _currentApp.value != null) {
      final duration = DateTime.now().difference(_lastSwitchTime!).inSeconds;
      final lastApp = _currentApp.value!.sourceAppName;
      _appUsageDuration[lastApp] = (_appUsageDuration[lastApp] ?? 0) + duration;
    }
    _lastSwitchTime = DateTime.now();
  }

  void _handleKeyPressEvent(KeyPressEvent keyEvent) {
    // 更新按键状态
    _lastKeyPress[keyEvent.keyName] = true;
    
    // 100毫秒后自动重置按键状态
    Future.delayed(const Duration(milliseconds: 100), () {
      _lastKeyPress[keyEvent.keyName] = false;
    });
  }

  void _handleNetworkTrafficEvent(NetworkTrafficEvent trafficEvent) {
    // 处理网络流量事件
    // 可以添加网络流量的统计等功能
  }
}
